import { ExecutionContext, Injectable, Logger } from '@nestjs/common';
import { ThrottlerGuard } from '@nestjs/throttler';
import * as requestIp from '@supercharge/request-ip';

@Injectable()
export class ThrottlerBehindProxyGuard extends ThrottlerGuard {
  protected errorMessage: string = '服务器繁忙';

  protected async getTracker(req: Record<string, any>): Promise<string> {
    const ip = requestIp.getClientIp(req);
    Logger.log(
      `IP: ${ip} - Url: ${req.url} Body: ${req.body ? JSON.stringify(req.body) : ''}  User: ${req.user?.id ?? ''} Mobile: ${
        req.user?.mobile ?? ''
      } Name: ${req.user?.realname ?? ''}`,
    );
    return req.user?.id ?? ip;
  }

  // protected async shouldSkip(context: ExecutionContext): Promise<boolean> {
  //   const req = context.switchToHttp().getRequest();
  //   const ip = requestIp.getClientIp(req);
  //   if (['59.172.108.160'].includes(ip)) {
  //     console.log(`白名单IP: ${ip}`);
  //     return true;
  //   }
  //   return false;
  // }

  protected generateKey(
    context: ExecutionContext,
    suffix: string,
    name: string,
  ): string {
    const req = context.switchToHttp().getRequest();
    const ip = requestIp.getClientIp(req);
    // return `throttler:${name}:${ip}:${suffix}`;
    return `throttler:${name}:${req.user?.id ?? ip}`;
  }
}
